package com.wxl.common.work

import androidx.appcompat.app.AppCompatActivity
import com.wxl.common.util.Loog
import com.wxl.common.viewmodel.AbsPresenter

abstract class AbsWork : AbsPresenter() {

    internal var mOnWorkCallback: OnWorkCallback? = null
    internal lateinit var context: AppCompatActivity
    internal lateinit var workKey:String

    override fun onCreated(vararg args: Any) {
        val arg = arrayListOf<Any>()
        if (args.isNotEmpty()) {
            context = args[0] as AppCompatActivity
            workKey = args[1] as String
            if(args.size > 2) {
                arg.addAll(args.toList().subList(2,args.size))
            }
            findCallback(*arg.toTypedArray())
        }
        onWorkCreate(*arg.toTypedArray())
    }



    /**
     * 找回调参数
     */
    private fun findCallback(vararg args: Any) {
        args.forEach {
            if (it is OnWorkCallback) {
                mOnWorkCallback = it
                return@forEach
            }
        }
    }

    /**
     * 任务创建时调用
     */
    abstract fun onWorkCreate(vararg args: Any)

    /**
     * 工作
     */
    abstract fun doWork(vararg args: Any)


    /**
     * 执行下一个任务
     */
    fun doNext(vararg args:Any){
        Work.doNext(workKey,context,*args)
    }

    /**
     * 重新开始任务
     */
    fun reStart(vararg args:Any){
        Work.reStart(workKey,context,*args)
    }

    /**
     * 跳到指定的任务开始执行
     */
    fun <W:AbsWork> toDoWork(work:Class<W>,vararg args:Any){
        Work.toDoWork(work,workKey,context,*args)
    }

    /**
     * 强制去执行一个任务，当在本任务池里没有时，new一个执行
     */
    fun <W:AbsWork> doWork(work:Class<W>,vararg args:Any){
        Work.exeWork(work,workKey,context,*args)
    }

    /**
     * 停止任务
     */
    fun stopWork(vararg args: Any){
        Work.stop(workKey)
        mOnWorkCallback?.onWorkResult(*args)
    }

    /**
     * 恢复任务为可执行
     */
    fun restore(){
        Work.restore(workKey)
    }

    /**
     * 重新开始本任务
     */
    fun retry(vararg args: Any){
        Work.retry(workKey,context,*args)
    }


    override fun onDestroy() {
        super.onDestroy()
        Work.release(workKey)
    }
}